<template>
	<view class="app-container">
		<input class="uni-input" v-model="deviceInfo.name" placeholder="请输入设备名称" />
		<button class="item" type="primary" @click="onItemClick(0)">修改设备名称</button>
		<button class="item" type="primary" @click="onItemClick(1)">发送dp数据</button>
		<button class="item" type="primary" @click="onItemClick(2)">获取设备固件列表</button>
		<view class="remove-device" @click="onRemoveDeviceClick">
			移除设备
		</view>
	</view>
</template>

<script>
	import {
		getDeviceInfo,
		removeDevice,
		renameDeviceName,
		onDpDataChange,
		publishCommands,
		connectBLEDevice,
		disconnectBLEDevice,
		getOTAInfo,
		checkOTAUpgrading,
		upgradeOTAInfo,
		onOTAUpgradeStatus,
		offOTAUpgradeStatus,
		onBLEConnectStatusChange,
		offBLEConnectStatusChange,
		getBLEOnlineState
	} from '@ray-js/wechat';
	export default {
		data() {
			return {
				deviceInfo: {
					name: ''
				},
				deviceId: '',
				itemData: {}
			}
		},
		onUnload() {
			// 退出时断开连接
			disconnectBLEDevice({
				deviceId: this.deviceId
			});
			//去除监听升级
			offOTAUpgradeStatus(this._handleOTAStatus)
			//去除蓝牙连接状态监听
			offBLEConnectStatusChange(this._handleBLEConnectStatus)
		},
		onLoad(options) {
			const {
				deviceId
			} = options
			this.deviceId = deviceId
			this._getDeviceInfo()
			this._onDpDataChange()
			this._onBLEConnectStatusChange()
			this._connectBLEDevice()
			this._onOTAUpgradeStatus()
			this._getBLEOnlineState()
		},
		methods: {
			async _getBLEOnlineState() {
				const response = await getBLEOnlineState({
					deviceId: this.deviceId,
				});
				console.log('连接成功_getBLEOnlineState', response);
			},
			//蓝牙连接状态
			_onBLEConnectStatusChange() {
				onBLEConnectStatusChange(data => this._handleBLEConnectStatus(data));
			},
			_handleBLEConnectStatus(data) {
				const {
					deviceId,
					status
				} = data
				if (deviceId === this.deviceId) {
					//status 状态值 CONNECTED:已连接 CONNECTING:连接中 CONNECT_BREAK:连接失败
					console.log('蓝牙连接状态', data);
					if (status === 'CONNECTED') {
						uni.showToast({
							icon: 'none',
							title: '蓝牙连接成功'
						})
						this._getBLEOnlineState()
					} else if (status === 'CONNECT_BREAK') {
						uni.showToast({
							icon: 'none',
							title: '蓝牙连接失败或断开，请查看设备启用状态'
						})
					}
				}
			},
			onItemClick(index) {
				switch (index) {
					case 0: //修改设备名称
						const {
							name
						} = this.deviceInfo
						if (!name) {
							uni.showToast({
								icon: 'none',
								title: '请输入设备名称'
							})
							return
						}
						this._renameDeviceName()
						break;
					case 1: //发送dp数据
						publishCommands({
							deviceId: this.deviceId,
							dps: {
								101: false,
							},
						})
						break
					case 2: //获取设备固件列表
						this._getOTAInfo()
						break
					default:
						break;
				}
			},
			//获取设备固件列表
			async _getOTAInfo() {
				//当前是否正在升级
				if (checkOTAUpgrading({
						deviceId: this.deviceId
					})) {
					uni.showToast({
						icon: 'none',
						title: '升级中'
					})
					return
				}
				const response = await getOTAInfo({
					deviceId: this.deviceId,
				});
				/**
				 * upgradeStatus 为当前 OTA 状态，// 0-不需要升级 1-硬件准备就绪,2-升级中,3-升级完成,4-升级异常
				 * moduleList 为固件列表
				 */
				const {
					upgradeStatus,
					moduleList
				} = response
				console.log(response);
				const list = moduleList.filter(item => item.moduleType === 1)
				if (list.length > 0) {
					this.itemData = list[0]
					uni.showModal({
						title: '固件信息',
						content: JSON.stringify(this.itemData),
						confirmText: '升级',
						success: (res) => {
							if (res.confirm) {
								const {
									currentVersion,
									upgradeVersion,
								} = this.itemData
								if (currentVersion === upgradeVersion) {
									uni.showToast({
										icon: 'none',
										title: '没有新的版本'
									})
									return
								} else if (upgradeStatus === 0) {
									uni.showToast({
										icon: 'none',
										title: '不需要升级'
									})
									return
								} else if (upgradeStatus === 2) {
									uni.showToast({
										icon: 'none',
										title: '升级中'
									})
									return
								} else if (upgradeStatus === 3) {
									uni.showToast({
										icon: 'none',
										title: '升级完成'
									})
									return
								} else if (upgradeStatus === 4) {
									uni.showToast({
										icon: 'none',
										title: '升级异常'
									})
									return
								}
								this._otaUpgrade()
							} else if (res.cancel) {
								uni.showToast({
									icon: 'none',
									title: '取消升级'
								})
							}
						}
					})
				}
			},
			//监听升级完成
			_onOTAUpgradeStatus() {
				onOTAUpgradeStatus(data => this._handleOTAStatus(data))
			},
			_handleOTAStatus(data) {
				// 判断是否为当前设备的升级状态变更
				const {
					deviceId,
					status
				} = data
				if (deviceId === this.deviceId) {
					if (status === 3) {
						//升级成功
						console.log('升级成功');
						uni.showModal({
							title: '提示',
							content: '升级成功'
						})
					} else if (status === 4) {
						// 升级失败
						console.log('升级失败');
						uni.showModal({
							title: '提示',
							content: '升级失败'
						})
					} else if (status === 2) {
						// 升级中
						console.log('升级中...');
					}
				}
			},
			//当存在待升级的固件时，用户可以点击升级
			_otaUpgrade() {
				upgradeOTAInfo({
					deviceId: this.deviceId,
					otaInfo: this.itemData,
				});
			},
			// 连接蓝牙
			_connectBLEDevice() {
				connectBLEDevice({
					deviceId: this.deviceId,
				});
			},
			//监听设备上报 DP
			_onDpDataChange() {
				onDpDataChange(data => {
					const {
						deviceId,
						dps
					} = data;
					console.log('接收DP数据', data);
				})
			},
			//修改设备名称
			async _renameDeviceName() {
				await renameDeviceName({
					deviceId: this.deviceId,
					name: this.deviceInfo.name,
				});
				uni.showToast({
					icon: 'none',
					title: '修改成功',
				})
				setTimeout(() => {
					uni.$emit('refreshDeviceList', true)
					uni.navigateBack({
						delta: 1
					})
				}, 1500);
			},
			//获取设备详细
			async _getDeviceInfo() {
				const response = await getDeviceInfo({
					deviceId: this.deviceId
				})
				this.deviceInfo = {
					...response
				}
			},
			//移除设备
			async onRemoveDeviceClick() {
				await removeDevice({
					deviceId: this.deviceId
				});
				uni.$emit('refreshDeviceList', true)
				uni.navigateBack({
					delta: 1
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.app-container {
		.uni-input {
			margin: 20upx 20upx 0;
			height: 75upx;
			padding-left: 25upx;
			padding-right: 25upx;
			border: 1upx solid #ccc;
		}

		.item {
			margin: 20upx 20upx 0;
		}

		.remove-device {
			background-color: blue;
			height: 75upx;
			width: 200upx;
			border-radius: 38upx;
			font-size: 28upx;
			position: fixed;
			left: 50%;
			margin-left: -100upx;
			bottom: 110upx;
			color: #fff;
			text-align: center;
			line-height: 75upx;
		}
	}
</style>